package com.flycms.filter;

import com.flycms.common.utils.HttpUtil;
import com.flycms.modules.site.entity.Site;
import com.flycms.modules.site.service.SiteService;
import com.flycms.modules.system.service.ConfigureService;
import com.flycms.modules.template.service.SiteTemplateTagsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Biz-Boot, All rights reserved
 * 版权：企业之家网 -- 企业建站管理系统<br/>
 * 开发公司：97560.com<br/>
 *
 * @author 孙开飞
 * @version 1.0 <br/>
 * @Description: 通用拦截器
 * @email 79678111@qq.com
 * @Date: 14:35 2019/11/21
 */
@Component
public class CommonInterceptor implements HandlerInterceptor {
    private Logger log = LoggerFactory.getLogger(CommonInterceptor.class);

    @Autowired
    private SiteTemplateTagsService siteTemplateTagsService;
    @Autowired
    private SiteService siteService;
    @Autowired
    private ConfigureService configureService;

    //用户自定义标签拦截器
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        if (!HttpUtil.isApiRequest(request) && modelAndView != null) {
            Site site = null;
            String domainString = com.flycms.common.utils.StringUtils.twoStageDomain(request.getRequestURL().toString());
            if (!StringUtils.isEmpty(domainString)) {
                site = siteService.findByDomain(domainString);
            } else {
                site = siteService.findById(Long.parseLong(configureService.findByKeyCode("default_site")));
            }
            if(!StringUtils.isEmpty(site.getId()) && !StringUtils.isEmpty(site.getTemplateId()) && site.getTemplateId() > 0){
                siteTemplateTagsService.selectSiteTemplateTagsList(site.getId(), site.getTemplateId()).forEach(str -> {
                    String prefix= "system_prefix";
                    modelAndView.addObject(configureService.findByKeyCode(prefix) + str.getTagKey(), str.getTagValue());
                });
            }
        }
    }
}
